package main

import (
	"bytes"
	"fmt"
	"io"
	"os"
	"os/exec"
	"path/filepath"
	"strings"
)

func main() {
	args := os.Args
	if len(args) < 2 {
		fmt.Println("缺少配置文件")
		return
	}

	configPath, err := filepath.Abs(args[1])
	if err != nil {
		fmt.Println("配置文件路径错误:" + err.Error())
	}
	configFile, err := os.Open(configPath)
	if err != nil {
		fmt.Println("读取配置文件错误:" + err.Error())
		return
	}
	defer configFile.Close()
	var b bytes.Buffer
	if _, err := io.Copy(&b, configFile); err != nil {
		fmt.Println("读取配置文件错误:" + err.Error())
		return
	}
	_ = configFile.Close()

	rArgsTemp := strings.Split(b.String(), "\n")
	rArgs := make([]string, 0, len(rArgsTemp))
	for _, t := range rArgsTemp {
		t = strings.TrimSpace(t)
		if t != "" {
			rArgs = append(rArgs, t)
		}
	}

	/*if ext := filepath.Ext(configPath); ext != ".yaml" {
		fmt.Println("配置文件后缀不支持:" + ext)
		return
	}

	viper.SetConfigName(strings.TrimRight(filepath.Base(configPath), filepath.Ext(configPath))) // name of config file (without extension)
	viper.SetConfigType("yaml")                                                                 // REQUIRED if the config file does not have the extension in the name
	viper.AddConfigPath(filepath.Dir(configPath))                                               // optionally look for config in the working directory
	if err := viper.ReadInConfig(); err != nil {
		fmt.Println("读取配置错误:" + err.Error())
		return
	}
	fmt.Printf("%+v\n", viper.AllSettings())
	return*/

	/*secretsFile := viper.GetString("secretsFile")
	excludeFrom := viper.GetString("excludeFrom")
	srcPath := viper.GetString("src")
	destPath := viper.GetString("dest")
	rArgs := []string{
		"--port=873",
		"-azvL",
		"--exclude-from=" + excludeFrom,
		"--password-file=" + secretsFile,
		srcPath,
		destPath,
	}*/
	c := exec.Command("rsync", rArgs...)
	fmt.Println(c.String())
	c.Stdout = os.Stdout
	c.Stderr = os.Stderr
	if err := c.Run(); err != nil {
		fmt.Println("rsync执行错误:" + err.Error())
		return
	}
}
